<template>
  <div class="hawkContent">
    <!-- 面包屑 -->
    <hawk-breadcrumb></hawk-breadcrumb>
    <!-- 搜索/添加 -->
    <el-row :gutter="20">
      <el-col :span="4" style="display:flex;align-items: center;">
        <span style="width:50px">名称</span>
        <el-input placeholder="请输入名称搜索" v-model="queryInfo.query.name">
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="hawkSearch" @click="init">搜索</el-button>
        <el-button plain @click="clearSearchData">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right; text-align: right; padding-right: 30px">
        <el-button type="hawkCreate" @click="addRow">创建角色</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <hawk-table v-model="multipleSelection" number :page="queryInfo.page"
                :table-data="tableData" :options="[
        { key: 'name', label: '角色名称' },
        { key: 'remark', label: '描述' },
        { key: 'createDate', label: '创建时间' },
        { key: 'updateDate', label: '更新时间' },
        { key: 'handle', label: '操作' }
      ]">
      <template #createDate="{ row }">
        <span>{{ transformDateFormat(row.createDate, 'yyyy-MM-dd hh:mm:ss') }}</span>
      </template>
      <template #updateDate="{ row }">
        <span>{{ transformDateFormat(row.updateDate, 'yyyy-MM-dd hh:mm:ss') }}</span>
      </template>
      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="permissionRow(row)">分配权限</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="editRow(row.id)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="delRow(row)">删除</span>
      </template>
    </hawk-table>
    <!-- 分页/多选操作 -->
    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="batchDelete">批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryInfo.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryInfo.page.size"
                     layout=" prev, pager, next,sizes"
                     :total="queryInfo.page.total">
      </el-pagination>
    </div>
    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="formTitle" :visible.sync="showEditForm"
               :close-on-click-modal="false" @close="closeEditForm">
      <el-form :model="addForm" label-position="top" :rules="formRules"
               ref="formRef" label-width="70px">
        <el-form-item label="名称" prop="name"
                      style="width:100%;margin-right:0px;">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" style="width:100%">
          <el-input type="textarea" :rows="2" placeholder="请输入内容"
                    v-model="addForm.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditForm = false">取 消</el-button>
        <el-button type="primary" @click="saveData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹窗 -->
    <el-dialog title="分配权限" :visible.sync="showPermissionForm" width="30%"
               :close-on-click-modal="false" @close="closePermission">
      <el-row>
        <el-col :span="20" :style="{fontSize:'8px'}">
          <h3>菜单权限</h3>
          <el-tree v-if="showPermissionForm" :data="menuPermissionList"
                   :props="defaultProps" :default-checked-keys="permissionIds"
                   node-key="id" ref="menuTree" show-checkbox
                   :check-strictly="loadType" check-on-click-node
                   default-expand-all>
          </el-tree>
        </el-col>
        <!-- <el-col :span="12">
          <h3>数据权限</h3>
          <h4>部门</h4>
          <el-select clearable
            v-model="permissionData.dataPermissionList.department"
            placeholder="请选择"
            multiple
            collapse-tags>
            <el-option-group
              v-for="group in departmentList"
              :key="group.label"
              :label="group.label">
              <el-option
                v-for="item in group.children"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
          <h4>业务系统</h4>
          <el-select clearable
            v-model="permissionData.dataPermissionList.business"
            multiple
            collapse-tags
            style="margin-left: 20px;"
            placeholder="请选择">
            <el-option
              v-for="item in businessList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col> -->
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPermissionForm = false">取 消</el-button>
        <el-button type="primary" @click="savePermission">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @author 罗冲
 * @description 角色管理
 * @api /system/role
 * @since 2021-11-08
 * @update 2021-11-30 10:59
 * @modifier 宋辉辉
 * @bug 无，新增接口访问
 * @version 版本号 例:v1.0.0
 */

import {
  getList,
  doEdit,
  doAdd,
  doDelete,
  exists,
  getById,
  assignPermission
} from '@/api/system/role'
import { doEdit as editMenu, getOne } from '@/api/system/roleMenu'
import { getTree } from '@/api/system/menu'
export default {
  data () {
    let checkRolename = async (rule, value, callback) => {
      let ret = await this.rolenameRules()
      if (ret) {
        callback(new Error('角色已存在'))
      }
      // else{
      //   callback()
      // }
    }
    return {
      // 菜单权限列表
      loadType: true,
      menuPermissionList: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      // 公司/部门列表
      departmentList: [],
      // 业务系统列表
      businessList: [],
      // 表格数据
      tableData: [],
      // 提交信息
      queryInfo: {
        query: {
          name: '',
        },
        page: {
          current: 1,
          size: 10,
          // 数据总量
          total: 0,
        },
      },

      // 多选数据
      multipleSelection: [],
      // 添加/编辑弹窗显示
      showEditForm: false,
      // 弹窗标题
      formTitle: '',
      // 弹窗表单
      addForm: {
        name: '',
        remark: '',
        status: 0,
      },
      // 验证表单
      formRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: checkRolename, trigger: 'blur' },
        ],
      },
      // 权限分配弹窗显示
      showPermissionForm: false,
      // 提交权限数据
      permissionIds: [],

      rolePermissionData: {
        menuId: [],
        roleId: 0
      }
    }
  },
  async created () {
    this.init()
    let res = await getTree(this.queryInfo.query.name);
    this.menuPermissionList = res.data
    console.log(this.menuPermissionList)
  },
  methods: {
    async init () {
      await getList(this.queryInfo).then((res) => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    // 验证用户名是否存在
    async rolenameRules () {
      let res = await exists(this.addForm.name)
      console.log(res)
      if (res.code === 20000) {
        return true
      } else {
        return false
      }
    },
    // 添加
    addRow () {
      this.showEditForm = true
      this.formTitle = '新增角色'
      console.log(this.addForm)
    },
    // 显示分配权限
    async permissionRow (row) {
      this.rolePermissionData.roleId = row.id
      let res = await getOne(row.id)
      // console.log(res)
      // console.log(res.data)
      this.permissionIds = res.data
      console.log(this.permissionIds)
      this.loadType = true
      this.showPermissionForm = true
      this.$nextTick(() => {
        this.loadType = false
      })
    },
    // 提交分配权限
    savePermission () {
      let list = this.$refs.menuTree.getCheckedNodes(false, true)
      let idList = []
      for (let i = 0; i < list.length; i++) {
        idList.push(list[i].id)
      }
      this.rolePermissionData.menuId = idList
      assignPermission(this.rolePermissionData)
      this.showPermissionForm = false
    },
    // 编辑
    async editRow (id) {
      await getById(id).then((res) => {
        this.addForm = res.data
        this.showEditForm = true
        this.formTitle = '编辑角色'
      })
    },
    // 添加/编辑提交
    async saveData () {
      console.log(this.addForm)
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return
        console.log(this.addForm)
        if (this.addForm.id) {
          doEdit(this.addForm)
        } else {
          doAdd(this.addForm)
        }
        this.$message({
          type: 'success',
          message: '操作成功',
        })
        this.closeEditForm()
      })
      await getList(this.queryInfo).then((res) => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    // 删除
    delRow (row) {
      this.$confirm(`此操作将删除数据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete([row.id])
          console.log(ret, '--------------ret----');

          if (ret.code == 20000) {

            let type = ''
            if (ret.data || ret.message.indexOf('成功') != -1) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }

            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            console.log('-------------init---');
            this.init()

          }
        })
        .catch(() => { })
    },
    // 批量删除
    batchDelete () {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'warning',
          message: '请选择需要删除的数据',
        })
        return
      } else {
        let idList = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          idList.push(this.multipleSelection[i].id)
        }
        this.$confirm(`此操作将删除数据, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(async () => {

            let ret = await doDelete(idList)
            console.log(ret, '--------------ret----');

            if (ret.code == 20000) {

              let type = ''
              if (ret.data || ret.message.indexOf('成功') != -1) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }


              this.$message({
                type: type,
                message: ret.message,
              })

              // console.log(this.multipleSelection.length);
              if (this.multipleSelection.length == this.tableData.length) {
                this.queryForm.page.current = this.queryForm.page.current - 1
                if (this.queryForm.page.current < 1) {
                  this.queryForm.page.current = 1
                }
              }

              this.multipleSelection = []
              console.log('-------------init---');
              this.init()

            }


          })
          .catch(() => { })
      }
    },
    // 重置搜索
    clearSearchData () {
      this.queryInfo = this.$options.data().queryInfo
      this.init()
    },
    // 改变页码
    handleCurrentChange (val) {
      this.queryInfo.page.current = val
      this.init()
      console.log(val)
    },
    // 改变数量
    handleSizeChange (val) {
      this.queryInfo.page.size = val
      this.init()
    },
    // 多选
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 关闭添加/编辑弹窗
    closeEditForm () {
      this.addForm = this.$options.data().addForm
      this.showEditForm = false
      this.init()
    },
    // 关闭权限弹窗
    closePermission () {
      this.showPermissionForm = false
    },
  },
}
</script>

<style lang="less" scoped>
.open {
  color: green;
}
/deep/.el-tree-node__label {
  font-size: 8px;
}
.close {
  color: red;
}

.el-select {
  margin-left: 0 !important;
}
</style>
